import { asyncRoutes, constantRoutes,notFoundRouter } from '@/router/index'
import { filterAsyncRoutes } from "@/utils/routes"
// state 存储数据
const state = {
  // 路由
  routes:[],
  // 动态路由
  addRoutes:[],
  // 缓存路由
  cacheRoutes:{},
}

// getters 对state数据进行加工
const getters ={
  permission_routes:state=> {
    return state.routes
  },
  // keepAliveRoutes: state=>{
  //   return filterKeepAlive(asyncRoutes)
  // }
}

// actions 响应组件中的事件
const actions = {
  // 生成路由
  generateRoutes({commit},roles){
    return new Promise(resolve => {
      // 在这判断是否有权限，哪些角色拥有哪些权限
      let accessedRoutes = []
      // roles 不是admin时，需要过滤异步路由信息
      if (roles&&roles.length&&!roles.includes('admin')) {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      } else {
        accessedRoutes = asyncRoutes || []
      }
      accessedRoutes = accessedRoutes.concat(notFoundRouter)

      const userRoutes = constantRoutes.concat(accessedRoutes)
      // 用户的全部路由信息
      commit("SET_ROUTES", userRoutes);
      // 动态路由信息
      commit("SET_ADD_ROUTES", accessedRoutes);
      resolve(accessedRoutes)
    })
  },
  // 清楚路由
  clearRoutes({commit}){
    commit("SET_ROUTES", []);
    commit("SET_ADD_ROUTES", []);
    commit("SET_CACHE_ROUTES", []);
  },
  // getCacheRoutes(){
  //   this.cacheRoutes = filterKeepAlive(asyncRoutes)
  //   return this.cacheRoutes
  // }
}

// mutations 操作数据
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_ADD_ROUTES: (state, addRoutes) => {
    state.addRoutes = addRoutes
  },
  SET_CACHE_ROUTES: (state, cacheRoutes) => {
    state.cacheRoutes = cacheRoutes
  },
}

// 暴露配置项在 index.js 自动生成对应的store
export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
